//
// Created by Tony on 2024/1/14.
//

#include "FileUtil.h"
#include <fstream>
#include <iostream>
#include <memory>

using std::make_shared;
using std::shared_ptr;
using std::string;

shared_ptr<SourceFile> FileUtil::readSourceFile(const string& fileName) {
    std::ifstream fileIn(fileName);
    if (!fileIn) {
        setErrMsg("failed open file <%s>", fileName.c_str());
        return nullptr;
    }

    auto sourceFile = make_shared<SourceFile>(fileName);
    string line;
    while (getline(fileIn, line)) {
        sourceFile->addLine(line);
    }

    fileIn.close();
    return sourceFile;
}

shared_ptr<BinaryFile> FileUtil::readBinaryFile(const string& filePath) {
    std::ifstream fileIn;

    fileIn.open(filePath, std::ios::in | std::ios::binary);
    if (!fileIn.is_open()) {
        return nullptr;
    }

    char* buffer = static_cast<char*>(malloc(BUFFER_SIZE));
    size_t count;
    auto binaryFile = make_shared<BinaryFile>(filePath);

    do {
        fileIn.read(buffer, BUFFER_SIZE);
        count = fileIn.gcount();
        binaryFile->append(buffer, count);
    } while (count == BUFFER_SIZE);

    free(buffer);
    return binaryFile;
}

void FileUtil::printSourceFile(const shared_ptr<SourceFile>& source) {
    for (const auto& line : source->getLines()) {
        std::cout << line << std::endl;
    }
}
